﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.InteropServices;
using System.IO;

namespace JavaReflectionLib
{
    class Utilities
    {
        [DllImport("user32.dll", EntryPoint = "GetWindowText", ExactSpelling = false, CharSet = CharSet.Auto, SetLastError = true)]
        private static extern int GetWindowText(int hWnd, StringBuilder lpWindowText, int nMaxCount);

        public static string GetWindowTitle(int pHandle, int nLen)
        {
            StringBuilder strbTitle = new StringBuilder(nLen);
            int nLength = GetWindowText(pHandle, strbTitle, strbTitle.Capacity + 1);
            return strbTitle.ToString();
        }

        public static int GetPortToSendRequest(string windowTitle)
        {
            int port = -1;

            if (File.Exists(Const.PATH_CONFIG))
            {
                string[] lines = File.ReadAllLines(Const.PATH_CONFIG);
                if (lines.Length > 0)
                {
                    foreach (string line in lines)
                    {
                        if (line.Trim().Length > 0)
                        {
                            string[] content = line.Split(new string[]{Const.TAB}, StringSplitOptions.RemoveEmptyEntries);
                            if (content.Length == 2)
                            {
                                if (content[0].ToLower().Equals(windowTitle.ToLower()))
                                {
                                    port = Int32.Parse(content[1]);
                                }
                            }
                        }
                    }
                }
            }

            return port;
        }

        public static string ReadResult(string action)
        {
            string result = "";

            if (File.Exists(Const.PATH_RESULT))
            {
                string[] lines = File.ReadAllLines(Const.PATH_RESULT);
                if (lines.Length > 0)
                {
                    foreach (string line in lines)
                    {
                        if (line.Trim().Length > 0)
                        {
                            string[] content = line.Split(new string[]{Const.TAB}, StringSplitOptions.RemoveEmptyEntries);
                            if (content.Length == 2)
                            {
                                if (content[0].ToLower().Equals(action.ToLower()))
                                {
                                    result = content[1];
                                }
                            }
                        }
                    }
                }
            }

            return result;
        }
    }
}
